import Router from "koa-router";
import { authMiddleware } from "../../../middleware/auth";
import { pool } from "../../../config/database";
import { RowDataPacket, ResultSetHeader } from "mysql2";
import bcrypt from "bcryptjs";
import { 
  checkAdminPermission, 
  getPaginationParams, 
  createPaginatedResponse, 
  getSearchParams,
  handleError,
  successResponse,
  validateId,
  validateBatchIds
} from "../common";

const router = new Router({ prefix: "/api/admin/users" });

// 获取用户列表 - 支持搜索和分页
router.get("/", authMiddleware, async (ctx) => {
  if (!checkAdminPermission(ctx)) return;
  
  try {
    const { page, limit, offset } = getPaginationParams(ctx);
    const { keyword, status, role, startDate, endDate } = getSearchParams(ctx);

    // 构建查询条件
    let whereClause = "WHERE 1=1";
    const params: any[] = [];

    if (keyword) {
      whereClause += " AND (username LIKE ? OR email LIKE ? OR nickname LIKE ?)";
      const searchTerm = `%${keyword}%`;
      params.push(searchTerm, searchTerm, searchTerm);
    }

    if (status) {
      whereClause += " AND status = ?";
      params.push(status);
    }

    if (role) {
      whereClause += " AND role = ?";
      params.push(role);
    }

    if (startDate) {
      whereClause += " AND created_at >= ?";
      params.push(startDate);
    }

    if (endDate) {
      whereClause += " AND created_at <= ?";
      params.push(endDate + ' 23:59:59');
    }

    // 获取总数
    const [countResult] = await pool.execute(
      `SELECT COUNT(*) as total FROM users ${whereClause}`,
      params
    ) as [RowDataPacket[], any];
    const total = countResult[0].total;

    // 获取用户列表
    const [users] = await pool.execute(`
      SELECT 
        id, username, email, nickname, role, status, phone, avatar,
        created_at, updated_at, loginIp
      FROM users 
      ${whereClause}
      ORDER BY created_at DESC
      LIMIT ${limit} OFFSET ${offset}
    `, params) as [RowDataPacket[], any];

    const response = createPaginatedResponse(users, total, page, limit);
    successResponse(ctx, response, "获取用户列表成功");

  } catch (error) {
    handleError(ctx, error, "获取用户列表失败");
  }
});

// 获取用户详情
router.get("/:id", authMiddleware, async (ctx) => {
  if (!checkAdminPermission(ctx)) return;
  
  try {
    const id = validateId(ctx);
    if (id === null) return;

    const [users] = await pool.execute(
      "SELECT id, username, email, nickname, role, status, phone, avatar, created_at, updated_at, loginIp FROM users WHERE id = ?",
      [id]
    ) as [RowDataPacket[], any];

    if (users.length === 0) {
      ctx.status = 404;
      ctx.body = { success: false, message: "用户不存在" };
      return;
    }

    successResponse(ctx, users[0], "获取用户详情成功");

  } catch (error) {
    handleError(ctx, error, "获取用户详情失败");
  }
});

// 创建用户
router.post("/", authMiddleware, async (ctx) => {
  if (!checkAdminPermission(ctx)) return;
  
  try {
    const { username, email, password, nickname, role = 'user', status = 'active', phone } = ctx.request.body as {
      username: string;
      email: string;
      password: string;
      nickname?: string;
      role?: string;
      status?: string;
      phone?: string;
    };

    // 基本验证
    if (!username || !email || !password) {
      ctx.status = 400;
      ctx.body = { success: false, message: "用户名、邮箱和密码为必填项" };
      return;
    }

    // 检查用户名和邮箱是否已存在
    const [existing] = await pool.execute(
      "SELECT id FROM users WHERE username = ? OR email = ?",
      [username, email]
    ) as [RowDataPacket[], any];

    if (existing.length > 0) {
      ctx.status = 400;
      ctx.body = { success: false, message: "用户名或邮箱已存在" };
      return;
    }

    // 密码加密
    const hashedPassword = await bcrypt.hash(password, 10);

    // 创建用户
    const [result] = await pool.execute(
      "INSERT INTO users (username, email, password, nickname, role, status, phone) VALUES (?, ?, ?, ?, ?, ?, ?)",
      [username, email, hashedPassword, nickname, role, status, phone]
    ) as [ResultSetHeader, any];

    const [newUser] = await pool.execute(
      "SELECT id, username, email, nickname, role, status, phone, created_at FROM users WHERE id = ?",
      [result.insertId]
    ) as [RowDataPacket[], any];

    successResponse(ctx, newUser[0], "用户创建成功");

  } catch (error) {
    handleError(ctx, error, "创建用户失败");
  }
});

// 更新用户信息
router.put("/:id", authMiddleware, async (ctx) => {
  if (!checkAdminPermission(ctx)) return;
  
  try {
    const id = validateId(ctx);
    if (id === null) return;

    const { username, email, nickname, role, status, phone } = ctx.request.body as {
      username?: string;
      email?: string;
      nickname?: string;
      role?: string;
      status?: string;
      phone?: string;
    };

    // 检查用户是否存在
    const [users] = await pool.execute(
      "SELECT id, username, email FROM users WHERE id = ?",
      [id]
    ) as [RowDataPacket[], any];

    if (users.length === 0) {
      ctx.status = 404;
      ctx.body = { success: false, message: "用户不存在" };
      return;
    }

    // 构建更新语句
    const updateFields: string[] = [];
    const updateValues: any[] = [];

    if (username !== undefined) {
      // 检查用户名是否已被其他用户使用
      const [existing] = await pool.execute(
        "SELECT id FROM users WHERE username = ? AND id != ?",
        [username, id]
      ) as [RowDataPacket[], any];

      if (existing.length > 0) {
        ctx.status = 400;
        ctx.body = { success: false, message: "用户名已被其他用户使用" };
        return;
      }

      updateFields.push("username = ?");
      updateValues.push(username);
    }

    if (email !== undefined) {
      // 检查邮箱是否已被其他用户使用
      const [existing] = await pool.execute(
        "SELECT id FROM users WHERE email = ? AND id != ?",
        [email, id]
      ) as [RowDataPacket[], any];

      if (existing.length > 0) {
        ctx.status = 400;
        ctx.body = { success: false, message: "邮箱已被其他用户使用" };
        return;
      }

      updateFields.push("email = ?");
      updateValues.push(email);
    }

    if (nickname !== undefined) {
      updateFields.push("nickname = ?");
      updateValues.push(nickname);
    }

    if (role !== undefined) {
      updateFields.push("role = ?");
      updateValues.push(role);
    }

    if (status !== undefined) {
      updateFields.push("status = ?");
      updateValues.push(status);
    }

    if (phone !== undefined) {
      updateFields.push("phone = ?");
      updateValues.push(phone);
    }

    if (updateFields.length === 0) {
      ctx.status = 400;
      ctx.body = { success: false, message: "没有提供要更新的字段" };
      return;
    }

    updateFields.push("updated_at = NOW()");
    updateValues.push(id);

    // 执行更新
    await pool.execute(
      `UPDATE users SET ${updateFields.join(", ")} WHERE id = ?`,
      updateValues
    );

    // 获取更新后的用户信息
    const [updatedUser] = await pool.execute(
      "SELECT id, username, email, nickname, role, status, phone, created_at, updated_at FROM users WHERE id = ?",
      [id]
    ) as [RowDataPacket[], any];

    successResponse(ctx, updatedUser[0], "用户信息更新成功");

  } catch (error) {
    handleError(ctx, error, "更新用户信息失败");
  }
});

// 重置用户密码
router.post("/:id/reset-password", authMiddleware, async (ctx) => {
  if (!checkAdminPermission(ctx)) return;
  
  try {
    const id = validateId(ctx);
    if (id === null) return;

    const { newPassword } = ctx.request.body as { newPassword: string };

    if (!newPassword || newPassword.length < 6) {
      ctx.status = 400;
      ctx.body = { success: false, message: "新密码不能为空，且长度不能少于6位" };
      return;
    }

    // 检查用户是否存在
    const [users] = await pool.execute(
      "SELECT id FROM users WHERE id = ?",
      [id]
    ) as [RowDataPacket[], any];

    if (users.length === 0) {
      ctx.status = 404;
      ctx.body = { success: false, message: "用户不存在" };
      return;
    }

    // 加密新密码
    const hashedPassword = await bcrypt.hash(newPassword, 10);

    // 更新密码
    await pool.execute(
      "UPDATE users SET password = ?, updated_at = NOW() WHERE id = ?",
      [hashedPassword, id]
    );

    successResponse(ctx, { id }, "密码重置成功");

  } catch (error) {
    handleError(ctx, error, "重置密码失败");
  }
});

// 批量更新用户状态
router.post("/batch-update-status", authMiddleware, async (ctx) => {
  if (!checkAdminPermission(ctx)) return;
  
  try {
    const ids = validateBatchIds(ctx);
    if (ids === null) return;

    const { status } = ctx.request.body as { status: string };

    if (!status) {
      ctx.status = 400;
      ctx.body = { success: false, message: "状态不能为空" };
      return;
    }

    const [result] = await pool.execute(
      `UPDATE users SET status = ?, updated_at = NOW() WHERE id IN (${ids.map(() => '?').join(',')})`,
      [status, ...ids]
    ) as [ResultSetHeader, any];

    successResponse(ctx, { 
      updatedCount: result.affectedRows,
      status 
    }, `批量更新状态成功，影响${result.affectedRows}个用户`);

  } catch (error) {
    handleError(ctx, error, "批量更新状态失败");
  }
});

// 删除用户（软删除）
router.delete("/:id", authMiddleware, async (ctx) => {
  if (!checkAdminPermission(ctx)) return;
  
  try {
    const id = validateId(ctx);
    if (id === null) return;

    // 检查用户是否存在
    const [users] = await pool.execute(
      "SELECT id, role FROM users WHERE id = ?",
      [id]
    ) as [RowDataPacket[], any];

    if (users.length === 0) {
      ctx.status = 404;
      ctx.body = { success: false, message: "用户不存在" };
      return;
    }

    // 软删除：更新状态为deleted
    await pool.execute(
      "UPDATE users SET status = 'deleted', updated_at = NOW() WHERE id = ?",
      [id]
    );

    successResponse(ctx, { id }, "用户删除成功");

  } catch (error) {
    handleError(ctx, error, "删除用户失败");
  }
});

// 批量删除用户
router.post("/batch-delete", authMiddleware, async (ctx) => {
  if (!checkAdminPermission(ctx)) return;
  
  try {
    const ids = validateBatchIds(ctx);
    if (ids === null) return;

    const [result] = await pool.execute(
      `UPDATE users SET status = 'deleted', updated_at = NOW() WHERE id IN (${ids.map(() => '?').join(',')})`,
      ids
    ) as [ResultSetHeader, any];

    successResponse(ctx, { 
      deletedCount: result.affectedRows 
    }, `批量删除成功，影响${result.affectedRows}个用户`);

  } catch (error) {
    handleError(ctx, error, "批量删除失败");
  }
});

// 获取用户统计信息
router.get("/statistics/overview", authMiddleware, async (ctx) => {
  if (!checkAdminPermission(ctx)) return;
  
  try {
    // 用户总体统计
    const [userStats] = await pool.execute(`
      SELECT 
        COUNT(*) as total_users,
        COUNT(CASE WHEN status = 'active' THEN 1 END) as active_users,
        COUNT(CASE WHEN status = 'inactive' THEN 1 END) as inactive_users,
        COUNT(CASE WHEN status = 'banned' THEN 1 END) as banned_users,
        COUNT(CASE WHEN role = 'admin' THEN 1 END) as admin_users,
        COUNT(CASE WHEN role = 'user' THEN 1 END) as regular_users,
        COUNT(CASE WHEN created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY) THEN 1 END) as new_users_week,
        COUNT(CASE WHEN created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY) THEN 1 END) as new_users_month
      FROM users WHERE status != 'deleted'
    `) as [RowDataPacket[], any];

    // 每日注册统计（最近30天）
    const [dailyStats] = await pool.execute(`
      SELECT 
        DATE(created_at) as date,
        COUNT(*) as user_count
      FROM users 
      WHERE created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)
        AND status != 'deleted'
      GROUP BY DATE(created_at)
      ORDER BY date DESC
    `) as [RowDataPacket[], any];

    successResponse(ctx, {
      overview: userStats[0],
      dailyRegistrations: dailyStats
    }, "获取用户统计成功");

  } catch (error) {
    handleError(ctx, error, "获取用户统计失败");
  }
});

export default router; 